<?php
namespace Kuoqi;

use Kuoqi;
/**
 * Class Resonse
 * @package Kuoqi
 * User kuoqi
 * Datetime 2022/2/28 11:08
 * Remark 核心组键 - 数据响应模块
 */
class Response{



    /**
     * @var string
     * User kuoqi
     * Datetime 2022/2/28 11:30
     * Remark 页面输出的类型信息
     */
    protected $content_type = '';

    /**
     * @var string
     * User kuoqi
     * Datetime 2022/2/28 11:30
     * Remark stream输出的内容信息
     */
    public $stream = '';

    /**
     * User kuoqi
     * Datetime 2022/2/28 11:31
     * Remark 解析核心参数到初始化
     * 解析，core,format的字段信息
     */
    public function init(){

        //todo--解析核心字段到输出模式

    }

    /**
     * @param $stream
     * User kuoqi
     * Datetime 2022/2/28 14:07
     * Remark 响应json输出
     */
    public function toJson($app){
        //配置请求头信息为json字段
        $this->content_type = 'application/json;charset=UTF-8';
        if(PHP_VERSION>='5.5'){
            $this->stream = json_encode($app->action_return,JSON_UNESCAPED_UNICODE);
        }else{
            $this->stream = json_encode($app->action_return);
        }
    }

    /**
     * @param $app
     * User kuoqi
     * Datetime 2022/3/1 18:27
     * Remark 响应json string 输出
     */
    public function toJsonString($app){
        //配置请求头信息为json字段
        $this->content_type = 'application/json;charset=UTF-8';
        $this->stream = $app->action_return;
    }

    /**
     * @param $app
     * @return Exception
     * User kuoqi
     * Datetime 2022/3/1 16:44
     * Remark 浏览器web输出
     */
    public function toWeb($app){
        //配置请求头信息为json字段
        $this->content_type = 'text/html;charset=UTF-8';
        //判定是否有layout
        if($app->layout_id){
            //有layout
            $file = new FileDriver($app->layout_id.'.html');
            $filecontent = $file->getContent();//获取文件内容
            $assign = array();
            $assign['_CONTENT_'] = $app->action_return;
            if(!$file->isValied()){
                return new Error($file->getError());
            }
            $stream = Interpreter::execCode($filecontent,Kuoqi::$app->getAssigns($assign));
            $tpid = Cache::setTemplate($stream);
            $this->stream = Cache::getTemplate($tpid,Kuoqi::$app->getAssigns($assign));
        }else{
            $this->stream = $app->action_return;
        }
    }


    /**
     * User kuoqi
     * Datetime 2022/2/28 11:30
     * Remark 响应输出
     */
    public function flush(){

        @header('Content-Type:'.$this->content_type);
        @header('Content-Length:'.strlen($this->stream));
        echo $this->stream;

    }
}